﻿using YiNing.UI.Forms;
using System.Windows.Forms;
using System.IO;
using System;
using YiNing.Tools;

namespace YiNing.Tools
{
    public partial class SelectProgram : DarkDialog
    {
        string ProgramPath = @"D:\QTWaferProgram";
        #region Constructor Region

        public SelectProgram()
        {
            InitializeComponent();
            this.btnOk.Text = "确定";
            this.btnCancel.Text = "取消";
            this.btnCancel.Click += BtnCancel_Click;
            this.Load += DialogSelectProgram_Load;
            this.FormClosing += DialogSelectProgram_FormClosing;
            this.cmbProgram.SelectedValueChanged += CmbProgram_SelectedValueChanged;
        }

        private void CmbProgram_SelectedValueChanged(object sender, EventArgs e)
        {
            cmbSubProgram.Items.Clear();
            TestProgramConfig programConfig = JsonHelper.DeserializeByFile<TestProgramConfig>(Path.Combine(ProgramPath, cmbProgram.Text, "config.zyn"));
            if (programConfig == null) return;
            cmbSubProgram.Items.AddRange(programConfig.GetSubprogramsDirName().ToArray());
        }

        private void DialogSelectProgram_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.DialogResult == DialogResult.Cancel || this.DialogResult == DialogResult.None)
            {
                return;
            }
            TestProgramConfig selectProgramConfig = JsonHelper.DeserializeByFile<TestProgramConfig>(Path.Combine(ProgramPath, cmbProgram.Text, "config.zyn"));
            if (selectProgramConfig == null)
            {
                DarkMessageBox.ShowWarning("选择的程式文件不存在，可能已被删除，请重试");
                this.DialogResult = DialogResult.Retry;
                e.Cancel = true;
                return;
            }
            selectProgramConfig.Id = tbWafweId.Text;
            selectProgramConfig.Name = cmbProgram.Text;
            if (!cmbSubProgram.Text.Equals(""))
            {
                selectProgramConfig = selectProgramConfig.GetSubprogram(cmbSubProgram.Text);
            }
            this.Tag = selectProgramConfig;
            this.DialogResult = DialogResult.OK;
        }

        private void BtnCancel_Click(object sender, System.EventArgs e)
        {
            this.Close();
        }

    
        private void DialogSelectProgram_Load(object sender, System.EventArgs e)
        {
            foreach (var f in SortAsFileCreationTime(ProgramPath))
            {
                cmbProgram.Items.Add(f.Name);
            }
        }



        /// <summary>
        　　/// C#按创建时间排序（倒序）
        　　/// </summary>
        　　/// <param name="arrFi">待排序数组</param>
        public DirectoryInfo[] SortAsFileCreationTime(string path)
        {
            DirectoryInfo root = new DirectoryInfo(path);
            var dicts = root.GetDirectories();
            Array.Sort<DirectoryInfo>(dicts, new FIleLastTimeComparer());
            return dicts;

        }
        #endregion
    }
}
